package com.kehutong.auth.service;

import com.kehutong.auth.entity.Account;
import com.kehutong.auth.entity.AccountLoginLog;
import com.kehutong.auth.enums.LoginMethod;
import com.kehutong.auth.enums.LoginType;
import com.kehutong.auth.util.IPSeeker;
import com.kehutong.common.DoveClient;
import com.kehutong.common.enums.UserType;
import com.kehutong.common.errcode.Result;
import com.kehutong.common.util.Token;
import org.coraframework.authz.AccessToken;
import org.coraframework.authz.AuthenticationInfo;
import org.coraframework.authz.SubjectUtil;
import org.coraframework.authz.exception.AuthenticationException;
import org.coraframework.authz.exception.IncorrectCredentialsException;
import org.coraframework.authz.exception.NotPermissionException;
import org.coraframework.authz.exception.UnknownAccountException;
import org.coraframework.inject.Inject;
import org.coraframework.inject.Singleton;
import org.coraframework.json.JSONObject;
import org.coraframework.logger.Logger;
import org.coraframework.logger.LoggerFactory;
import org.coraframework.orm.Pool;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.util.CallBack;

/**
 * 客户登陆
 *
 * @author liuzhen
 */
@Singleton
public class LoginCustomerService {

    private static final Logger logger = LoggerFactory.getLogger(LoginCustomerService.class);

    @Inject
    private DoveClient doveClient;
    @Inject
    private JdbcSession jdbcSession;
    @Inject
    private AccountService accountService;
    @Inject
    private LoginEmployeeService loginEmployeeService;


    // 密码登陆
    public Object logingByPass(String username, String password) throws Exception {
        return login(LoginType.EMPLOYEE_PASS, username, password, token -> {
            token.setUserType(UserType.system);
        });
    }

    public Object loginByMini(JSONObject jsonObject) throws Exception {
        String ip=jsonObject.getString("ip");
        //获取小程序相关接口
        JSONObject rs = doveClient.post("/kht-bin/wechat/getUserInfo", http -> {
            http.addParam("appId", jsonObject.getString("appId"));
            http.addParam("code", jsonObject.getString("code"));
            http.addParam("iv", jsonObject.getString("iv"));
            http.addParam("encryptedData", jsonObject.getString("encryptedData"));
        });

        int code = rs.getIntValue("code");
        if (code != 200) {
            return Result.error(code, rs.getString("message"));
        }

        JSONObject userInfo = rs.getJSONObject("data");
        if (userInfo.getBooleanValue("created")) {
            //首次绑定账号更新账户昵称与头像
            String id=userInfo.getString("uuid");
            String nickName=jsonObject.getString("nickName");
            String avatar=jsonObject.getString("avatarUrl");
            jsonObject.put("id",id);
            jsonObject.put("nickName",nickName);
            jsonObject.put("avatar",avatar);
            accountService.saveOrUpdateAccount(jsonObject);
        }

        return login(LoginType.CUSTOMER_AUTHOR, userInfo.getString("uuid"), "kehutong@2020", token -> {
            token.setSuiteId(jsonObject.getString("appId"));
        });
    }

    /**
     * 公众号授权
     */
    public Object loginByMp(JSONObject jsonObject) throws Exception {
        //获取小程序相关接口
        JSONObject rs = doveClient.post("/kht-bin/wechat/getMpUserInfo", http -> {
            http.addParam("appId", jsonObject.getString("appId"));
            http.addParam("code", jsonObject.getString("code"));
        });

        int code = rs.getIntValue("code");
        if (code != 200) {
            return Result.error(code, rs.getString("message"));
        }
        return rs;
    }

    // 登陆处理
    protected Object login(LoginType type, String username, String password, CallBack<Token> call) throws Exception {
        try {
            AuthenticationInfo authInfo = new AuthenticationInfo(username, password, type);
            AccessToken accessToken = SubjectUtil.getSubject().login(authInfo);

            Account account = Pool.get(Account.class, accessToken.getUserId());

            Token token = Token.create();
            token.setSessionId(accessToken.getSessonId());
            token.setUuid(account.getId());
            token.setUsername(account.getNickName());
            token.setMobile(account.getMobile());
            token.setHeadUrl(account.getAvatar());
            token.setUserType(UserType.webchat);
            token.setUserCreateTime(account.getCreateTime().getTime());
            call.call(token);
            loginEmployeeService.onLogin(token);
            return token;
        } catch (NotPermissionException e) {
            logger.info("验证码验证失败");
            return Result.error(0002, "您输入的验证码不正确");
        } catch (UnknownAccountException e) {
            // UserUtils.increaseLoginErrorCount(username);
            return Result.error(0001, "您输入的帐号或密码有误");
        } catch (IncorrectCredentialsException e) {
            return Result.error(0001, "您输入的帐号或密码有误");
        } catch (AuthenticationException e) {
            return Result.error(0, e.getMessage());
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return Result.error(0, e.getMessage());
        }
    }
}